package org.gavin.core.domain;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.gavin.core.constant.HttpStatus;
import org.gavin.core.enums.CommonStatus;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author Lion Li
 */
@Data
@NoArgsConstructor
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;


    private int code;

    private String msg;

    private T data;

    public static <T> R<T> ok() {
        return restResult(null, CommonStatus.OK.getCode(), CommonStatus.OK.getMsg());
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, CommonStatus.OK.getCode(), CommonStatus.OK.getMsg());
    }

    public static <T> R<T> ok(String msg) {
        return restResult(null, CommonStatus.OK.getCode(), msg);
    }

    public static <T> R<T> ok(String msg, T data) {
        return restResult(data, CommonStatus.OK.getCode(), msg);
    }

    public static <T> R<T> ok(Status status) {
        return restResult(null, status);
    }

    public static <T> R<T> ok(Status status, T data) {
        return restResult(data, status);
    }

    public static <T> R<T> fail() {
        return restResult(null, CommonStatus.fail.getCode(), CommonStatus.fail.getMsg());
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, CommonStatus.fail.getCode(), msg);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, CommonStatus.fail.getCode(), CommonStatus.fail.getMsg());
    }

    public static <T> R<T> fail(String msg, T data) {
        return restResult(data, CommonStatus.fail.getCode(), msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> fail(Status status) {
        return restResult(null, status);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static <T> R<T> warn(String msg) {
        return restResult(null, HttpStatus.WARN, msg);
    }

    /**
     * 返回警告消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static <T> R<T> warn(String msg, T data) {
        return restResult(data, HttpStatus.WARN, msg);
    }

    public R<T> data(T data) {
        this.data = data;
        return this;
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }

    private static <T> R<T> restResult(T data, Status status) {
        R<T> r = new R<>();
        r.setCode(status.getCode());
        r.setData(data);
        r.setMsg(status.getMsg());
        return r;
    }

    public static <T> Boolean isError(R<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(R<T> ret) {
        return CommonStatus.OK.getCode() == ret.getCode();
    }
}
